<?php
/** .-------------------------------------------------------------------
 * | Author: OkCoder <1046512080@qq.com>
 * | Git: https://www.gitee.com/okcoder
 * | Copyright (c) 2012-2019, www.i5920.com. All Rights Reserved.
 * '-------------------------------------------------------------------*/


if (!function_exists('api')) {
// API接口返回格式
    function api($data, $status = 200, array $header = [], $type = 'html')
    {
        $key = env('AES_KEY', '0987654321fedcba');
        $iv = env('AES_IV', '0987654321fedcba');
        $aes = new \OkCoder\PHPAes\Main($key, $iv);
        if (is_array($data)) {
            $data = json_encode($data);
        }
        $data = $aes->encrypt($data);
        response($data, $status, $header, $type)->send();
    }
}

if (!function_exists('parseInput')) {
    /**
     * 获取输入数据 支持默认值和过滤
     *
     * @param string $key     获取的变量名
     * @param mixed  $default 默认值
     * @param string $filter  过滤方法
     *
     * @return mixed
     */
    function parseInput($key = '', $default = null, $filter = '')
    {
        if (0 === strpos($key, '?')) {
            $key = substr($key, 1);
            $has = true;
        }

        if ($pos = strpos($key, '.')) {
            // 指定参数来源
            $method = substr($key, 0, $pos);
            if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
                $key = substr($key, $pos + 1);
            } else {
                $method = 'param';
            }
        } else {
            // 默认为自动判断
            $method = 'param';
        }
        $aesData = input($method . '.data');
        $textData = json_decode((new \OkCoder\PHPAes\Main(env('AES_KEY'), env('AES_IV')))->decrypt($aesData), true);

        if (isset($has)) {
            return isset($textData[$key]) ? true : false;
        } else {
            if ($key) {
                $res = (isset($textData[$key]) && $textData[$key]) ? $textData[$key] : $default;
                if ($filter) $res = $filter($res);
                return $res;
            } else {
                return $textData;
            }
        }
    }
}
